package com.rw.controller;

import com.rw.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "updateMoneyServelt",value = "/updateMoney")
public class UpdateMoneyServelt extends HttpServlet {

    private AccountService accountService;

    @Override
    public void init() throws ServletException {
        super.init();
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationcontext.xml");
        this.accountService = (AccountService) ac.getBean("accountService");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //执行转账逻辑
        request.setCharacterEncoding("utf-8");
        //1.获取参数：
        //注意:如果说是前后端分离的项目，那么这些参数最好在校验一次
        //非前后端分离的项目，可以不用校验
        Integer aid = Integer.parseInt(request.getParameter("aid"));
        Double money = Double.parseDouble(request.getParameter("money"));
        Integer inUid = Integer.parseInt(request.getParameter("inAid"));
        //2.在service中进行转账操作
        try {
          boolean flag = this.accountService.getMoney(aid, money, inUid);
          //针对转账成功或者失败进行处理
            if (flag){
                //成功的操作
                request.getSession().setAttribute("msg",true);
            }else {
                //失败的操作
                request.getSession().setAttribute("msg",false);
            }
            response.sendRedirect("./msg.jsp");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //3.返回信息到浏览器
    }
}
